const mongoose  = require('mongoose')
const { options } = require('../model/schema')
const {SuccessModel, ErrorModel} = require('../model/response')
const jwtCheck = require('../util/jwt')
const express = require('express')

const router = express.Router()


/**
 * 查询设置
 */
router.get('/options', (req, res)=>{
    options.findOne({username: req.query.username}, (err, docs)=>{
        if(err) return res.json(new ErrorModel(err))
        res.json(new SuccessModel(docs))
    })
})


/**
 * 查询设置
 */
 router.post('/options/update', (req, res)=>{
    const data = req.body
    // 用户不存在则创建用户
    options.findOne({username: data.username}, (err, doc)=>{
        if(!doc) {
            data.options['username'] = data.username
            const tempData = data.options
            options.create({
                ...tempData
            }, (err, doc)=>{
                if(err) return res.json(new ErrorModel(err))
                res.json(new SuccessModel('初始化基本设置成功'))
            })
        }
        // 存在则更新
        else {
            options.update(
                {username: data.username},
                {
                    ...data.options
                }
            ).then(()=>{
                res.json(new SuccessModel('更新成功'))
            }).catch((err)=>{
                res.status(400).json(new ErrorModel('更新失败！'))
            })
        }
    })

    
})


module.exports = router